package T1.controller;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Blob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;

/**
 *
 * @author William Monteiro <wmonteiro at inf.ufsm.br>
 */
@ManagedBean
@RequestScoped
public class manipulaImagem extends T1.view.Produto{

    public manipulaImagem() {
    }
    
    public void imgToMemo(){
        setFileImg(new File(getImagem()));
        int tamanho = (int) getFileImg().length();
        
    }

    public void manipulaImagemBanco() {
        //FileOutputStream image;
        Connection conn = null;
        PreparedStatement pstmt = null;
        Statement stmt = null;
        ResultSet res = null;
        StringBuffer query = null;
        String filename = "c:/backblue.gif";

        try {
            query = new StringBuffer("insert into blobs(filename,binarydata,name) values (?,?,?)");
            File file = new File(filename);

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "raghu123");
            stmt = conn.createStatement();
            pstmt = conn.prepareStatement(query.toString());
            pstmt.setString(1, filename);
            pstmt.setBinaryStream(2, new FileInputStream(filename), (int) file.length());
            pstmt.setString(3, "silviya");
            pstmt.executeUpdate();
            System.out.println("Successfully inserted into BLOBS .....");

            ResultSet rs = stmt.executeQuery("select * from blobs where name='silviya'");
            if (rs.next()) {
                Blob test = rs.getBlob("binarydata");
                InputStream x = test.getBinaryStream();
                int size = x.available();
                OutputStream out = new FileOutputStream("c:/xyz.gif");
                byte b[] = new byte[size];
                x.read(b);
                out.write(b);
            }
        } catch (ClassNotFoundException cnfe) {

            System.out.println("ClassNotFoundException occured :" + cnfe);
        } catch (SQLException se) {

            System.out.println("SQLException occured :" + se);
        } catch (FileNotFoundException fe) {

            System.out.println("File Not Found Exception occured :" + fe);
        } catch (Exception e) {

            System.out.println("Exception occured :" + e);
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (Exception e) {
            }
        }
    }
}
